/**
 * 正在登录本客户端的用户Customer及其相关配置
 */
import { isrememberLogin } from '@/api/customer'
import { isNullOrUndefind, JsonExcludeNullOrUndefind } from '../utils/utils';
const state = {
  // customer:{
  //     id:undefined,
  //     name:undefined,
  //     password:undefined,
  //     nickname:undefined,
  //     phone:undefined,
  //     address:undefined, //收货地址
  // },
  // //账号登录相关 非账户信息
  // account:{
  //     // 登录时间
  //     time:undefined,
  //     ip:undefined,//登录ip
  //     token:undefined,//token 
  // }
  customer: null,
  //账号登录相关 非账户信息
  account: null


}
const actions = {
  login(context, state) {
    const customer = state.customer;
    const account = state.account;

    //  console.log(JSON.stringify(account)+'#'+JSON.stringify(customer))
    context.commit('login', { customer, account })
  },
  /**
   * 是否已登录或者记住了登录
   * @param {} context 
   */
  isLogin(context) {
    // console.log('是否已登录或者记住了登录')
    //初始化app.vue或者刷新页面
    let jsoncustomer = window.sessionStorage.getItem('customer');
    let jsonaccount = window.sessionStorage.getItem('account');
    if (jsonaccount !== null && jsoncustomer !== null) {
      // console.log('sess')
      context.commit('login', {
        customer: JSON.parse(jsoncustomer),
        account: JSON.parse(jsonaccount)
      })
    } else {
      jsoncustomer = window.localStorage.getItem('customer');
      jsonaccount = window.localStorage.getItem('account');
      if (jsonaccount !== null && jsoncustomer !== null) {
        // console.log('loc')
        //向后台发送请求用户信息是否发送改变
        isrememberLogin(JSON.parse(jsoncustomer), JSON.parse(jsonaccount)).then(res => {
          // console.log('记住')
          context.commit('login', {
            customer: res.customer,
            account: res.account
          })
        })
      }
    }
  }
}

const getters = {

}
const mutations = {
  login(state, res) {
    state.account = res.account;
    state.customer = res.customer
    // console.log(res.customer)
    window.sessionStorage.setItem('customer', JsonExcludeNullOrUndefind(res.customer))
    window.sessionStorage.setItem('account', JsonExcludeNullOrUndefind(res.account))
    if (isNullOrUndefind(window.localStorage.getItem('customer') && isNullOrUndefind(window.localStorage.getItem('account')))) {
      window.localStorage.setItem('customer', JsonExcludeNullOrUndefind(res.customer))
      window.localStorage.setItem('account', JsonExcludeNullOrUndefind(res.account))
    }
  },
  logout(state) {
    state.account = null;
    state.customer = null;
    window.sessionStorage.removeItem('customer')
    window.sessionStorage.removeItem('account')
    window.localStorage.removeItem('customer')
    window.localStorage.removeItem('account')
  }
}
export default {
  namespaced: true,
  state,
  actions,
  getters,
  mutations
}